package com.ymt.consumer.listener;

import com.ymt.common.tools.JsonWrapper;
import com.ymt.consumer.domain.FinancialReceipts;
import com.ymt.consumer.service.FinancialReceiptsService;
import com.ymt.consumer.utils.FinancialReceiptsFactory;
import com.ymt.producer.domain.Order;
import com.ymt.reliable.message.service.TransactionMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

@Service
public class ConsumerListener implements MessageListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerListener.class);

    @Autowired
    private TransactionMessageService transactionMessageService;
    @Autowired
    private FinancialReceiptsService financialReceiptsService;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Override
    public void onMessage(Message message) {
        final TextMessage textMessage = (TextMessage) message;
        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                boolean success = false;
                String messageId = "";
                try {
                    messageId = textMessage.getStringProperty("messageId");
                    Order order = JsonWrapper.readValue(textMessage.getText(), Order.class);
                    FinancialReceipts financialReceipts = FinancialReceiptsFactory.create(order);

                    //保证业务幂等性
                    if (!financialReceiptsService.alreadyReceipt(order.getOrderCode())) {
                        financialReceiptsService.recordReceipt(financialReceipts);
                    }
                    success = true;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (success) {
                        transactionMessageService.delete(messageId);
                        LOGGER.info(">>> 业务执行成功删除消息! messageId:{}", messageId);
                    }
                }
            }
        });
    }
}
